<template>
  <div>
    <el-dialog
      :title="checkRoomName ? checkRoomName + '--机房号源比例批量修改' : '机房号源比例批量修改'"
      width="90%"
      top="50px"
      :visible.sync="tfdVisible"
      :before-close="closeTempDlg"
      class="ky-dialog"
    >
      <div class="tfd-main">
        <div class="appo-header" v-if="tfdVisible && !checkRoomName">
          <section class="">
            <div class="flex flex-row justify-start align-center">
              <el-select class="m-t-1" size="small" v-model="checkRoom" placeholder="请选择检查机房" clearable filterable>
                <el-option
                  v-for="(item,index) in checkRoomOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <el-button type="primary" class="mar-l-10" size="small" @click="search" plain><i class="el-icon-search"></i><span class="mar-l-3">搜索</span></el-button>
            </div>
          </section>
          <div style="float: right;">
          </div>
        </div>
        <div class="appo-main h-100">
          <fullschedule v-show="appoClassify.length > 0" :week-arr="weekArr" :scheduledata="appoClassify" :from="'numberRules'"></fullschedule>
          <div class="ky-listnone" v-show="checkRoom == '' && appoClassify.length == 0">请选择检查机房</div>
        </div>
      </div>
      <div slot="footer" class="efd-footer">
        <el-button size="small" @click="closeTempDlg">取消</el-button>
        <el-button size="small" type="primary" @click="saveBtn">保存</el-button>
      </div>
    </el-dialog>
    <!-- 查看预约信息详情 -->
    <appoReleaseInfo
      ref="appoReleaseInfo"
    ></appoReleaseInfo>
  </div>
</template>

<script>
import bus from '@/api/bus'
import { getHospitalSetting, getnumberscalerulelist, setnumberscalerulelist } from '@/api/api'
import {
  getAppointmentTempList,
  getAppTempAppointmentlistRoom
} from '@/api/room'
import fullschedule from './components/fullschedule'
// import week from '../components/week'
import appoReleaseInfo from '@/views/scheduling/components/appoReleaseInfo'
// import roomCascader from '@/views/scheduling/components/roomCascaderBase'
import { dateFormatter } from '@/utils/validate'
import { Options } from '@/utils/constant'
import { weekArrSort, setSidebarDataTemp } from '@/utils/utils' // this.$utils
import { getWeekStartEndDate, seasonCalCurrDate } from '@/utils/schedule'
// import roomNone from '@/components/roomNone'
// import aes from '@/utils/aes'
export default {
  // roomCascader, fullschedule, roomNone
  components: { fullschedule, appoReleaseInfo },
  props: {
    checkRoomName: {
      type: String,
      default: ''
    },
    hospitalCode: {
      type: String,
      default: ''
    },
    checkRoomOptions: {
      type: Array,
      default: []
    },
    allCheckbox: {
      type: Boolean,
      default: false
    },
    templateType: {
      type: String,
      default: 'template' // schedule
    }
  },
  data() {
    return {
      loading: false,
      appointmentData: [],
      curDate: dateFormatter(new Date()),
      checkRomeArr: [], // 查询数据机房联级数组
      checkRoom: '',
      // 机房，查询条件数据
      checkRoomObj: {
        HospitalCode: '',
        StartDate: '',
        EndDate: '',
        DepArea: '',
        Dep: '',
        ModalityType: '',
        CheckRoom: '',
        AppointmentStatus: '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班；单选
        IsHasFilters: true
      },
      tfdVisible: false,

      // 排班条件
      appoFormData: {
        room: [],
        month: '',
        week: '',
        day: '',
        type: false,
        status: 'week' // week: 周，day: 日
      },
      weekDateFull: [],
      appoList: [],
      appoClassify: [],
      weekArr: Options.weekOptions,
      // 排班
      fullscheduleIsEdit: false,
      sidebardata: [],
      statusFilter: '暂停预约、节假日、正常预约、设备故障、计划排班',
      updateAppoList: []
    }
  },
  watch: {
    tfdVisible: {
      handler(val) {
        if (val) {
          if (this.checkRoomName) {
            this.checkRoom = this.checkRoomName
            this.fetchData()
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.updateAppoList = []
    bus.$off('updateItem').$on('updateItem', (item) => {
      console.log('item.id', item.id)
      console.log('item', item)
      // appo => appo.timeInterval == item.timeInterval && appo.week == item.week && item.numberType == appo.numberType && item.numType == appo.numType
      let index = this.updateAppoList.findIndex(appo => appo.id == item.id)
      console.log('updateItem=>index', index)
      if (index > -1) {
        this.updateAppoList[index].num = Number(item.num)
      } else {
        item.num = Number(item.num)
        this.updateAppoList.push(item)
      }
      console.log('updateAppoList', this.updateAppoList)
    })
  },
  created() {
    console.log('created=>templateFullscheduleDialog')
  },
  beforeDestroy() {
    console.log('beforeDestroy=>templateFullscheduleDialog')
  },
  methods: {
    saveBtn() {
      // 保存所修复过的号源比例
      let params = {
        hospitalCode: this.hospitalCode,
        list: this.updateAppoList
      }
      setnumberscalerulelist(params).then(res => {
        if (res && res.code === 10000) {
          this.$message.success(res.message)
          this.tfdVisible = false
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    search() {
      // console.log('checkRoomOptions', this.checkRoomOptions)
      this.fetchData()
    },
    fetchData() {
      let prams = {
        checkRoom: this.checkRoom,
        hospitalCode: this.hospitalCode
      }
      this.loading = true
      console.log('prams', prams)
      getnumberscalerulelist(prams).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          let appoList = res.content.list
          let week = res.content.weekList
          const resultWeekArr = weekArrSort(week)
          this.weekArr = resultWeekArr.map(item => item.week)
          this.appoList = appoList
          let appoClassify = []
          appoList.forEach(item => {
            this.weekArr.forEach((week, index) => {
              if (!appoClassify[index]) {
                appoClassify[index] = []
              }
              if (item.week == week) {
                appoClassify[index].push(item)
              }
            })
          })
          this.appoClassify = appoClassify
          bus.$emit('getAppoClassify', appoClassify)
        } else {
          this.appoClassify = []
          bus.$emit('getAppoClassify', this.appoClassify)
        }
      })
    },
    async init(data, iDate) {
      console.log('init')
      this.curDate = dateFormatter(new Date(iDate), false)
      this.tfdVisible = true
      this.updateAppoList = []
      this.appoClassify = []
      bus.$emit('getAppoClassify', this.appoClassify)
      console.log('appoClassify', this.appoClassify)
      // if (data) {
      //   const _iDate = new Date(dateFormatter(iDate || this.curDate, false)).getTime()
      //   const _cDate = new Date(dateFormatter(this.curDate, false)).getTime()
      //   if (JSON.stringify(this.checkRomeArr) === JSON.stringify(data) && _iDate === _cDate) return false
      //   console.log('机房改变===前', this.checkRomeArr)
      //   this.appoFormData.room = data
      //   this.checkRomeArr = [...data]
      //   this.checkRoomObj.HospitalCode = data[0]
      //   this.checkRoomObj.DepArea = data[1]
      //   this.checkRoomObj.Dep = data[2]
      //   this.checkRoomObj.ModalityType = data[3]
      //   this.checkRoomObj.CheckRoom = data[4]
      //   this.checkRoomObj.AppointmentStatus = ''
      //   await this.getWeekDateTimeFull()
      //   await this.getAppoTimeTemp()
      //   this.curDate = dateFormatter(new Date(_iDate), false)
      //   this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata })
      //   this.getAppoTempList()
      // }

      // this.$nextTick(() => {
      //   this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata })
      // })
    },
    // 机房改变
    async roomChange(roomData) {
      if (roomData && roomData.length > 0) {
        console.log('机房改变====', roomData)
        this.checkRomeArr = [...roomData]
        this.checkRoomObj.HospitalCode = roomData[0]
        this.checkRoomObj.DepArea = roomData[1]
        this.checkRoomObj.Dep = roomData[2]
        this.checkRoomObj.ModalityType = roomData[3]
        this.checkRoomObj.CheckRoom = roomData[4]
        this.checkRoomObj.AppointmentStatus = ''
        await this.getWeekDateTimeFull()
        await this.getAppoTimeTemp()
        this.$nextTick(() => {
          this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata })
        })
        this.getAppoTempList()
      } else {
        this.checkRomeArr = []
        this.checkRoomObj.HospitalCode = ''
        this.checkRoomObj.DepArea = ''
        this.checkRoomObj.Dep = ''
        this.checkRoomObj.ModalityType = ''
        this.checkRoomObj.CheckRoom = ''
        this.weekDateFull = []
      }
    },
    // 查看、编辑预约排班信息
    handleAppoInfo(data) {
      // console.log(data)
      // this.$refs.appoReleaseInfo.init(data.appoInfo)
    },
    // 查询，获取排班模板数据
    async getAppoTempList() {
      this.loading = true
      const appodata = this.templateType === 'template'
        ? await getAppointmentTempList(this.checkRoomObj)
        : await getAppTempAppointmentlistRoom(this.checkRoomObj)

      this.loading = false
      console.log('查询，获取排班模板数据 getAppoTempList', JSON.parse(JSON.stringify(appodata)))
      this.$nextTick(() => {
        this.$refs.fullschedule.appoPull(appodata)
      })
    },
    // 获取时段数据,计算时段
    getAppoTimeTemp() {
      return new Promise(async resolve => {
        const param = {
          HospitalCode: this.checkRoomObj.HospitalCode
        }
        await getHospitalSetting(param).then(async res => {
          if (res && res.code === 10000) {
            // 获取模板的时间轴
            const season = await seasonCalCurrDate(res.content.seasonSettings, this.weekDateFull[0], true, false, true)
            this.sidebardata = season.sidebardata
            setSidebarDataTemp(JSON.stringify(season.sidebardata))
          }
        })
        resolve()
      })
    },
    // 获取排班一周的完整时间数组
    getWeekDateTimeFull() {
      return new Promise(async resolve => {
        this.weekDateFull = await getWeekStartEndDate(this.curDate)
        console.log('this.weekDateFull', this.weekDateFull)
        if (this.weekDateFull.length > 0) {
          this.checkRoomObj.SelectDate = this.weekDateFull[0]
          this.checkRoomObj.StartDate = this.weekDateFull[0]
          this.checkRoomObj.EndDate = this.weekDateFull[this.weekDateFull.length - 1]
        }
        resolve()
      })
    },
    // 导入模式变化
    statusChange(val) {
      // console.log(val)
      this.fullscheduleIsEdit = val === 'day'
    },
    // 关闭
    closeTempDlg() {
      this.tfdVisible = false
      this.$emit('closeTempDlg')
    }
  }
}
</script>

<style lang="scss" scoped>
.tfd-main{
  padding: 0 15px;
  min-height: 500px;
}
.appo-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-line-36 /deep/ .el-form-item__content{
  line-height: 36px;
}
</style>
